package com.gblw.rjkf.pj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gblw.rjkf.pj.entity.SysPermissions;
import com.gblw.rjkf.pj.mapper.SysPermissionsMapper;
import com.gblw.rjkf.pj.service.SysPermissionsService;
import com.gblw.rjkf.pj.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * SysPermissionsServiceImpl(SysPermissions)
 *
 * @author wj
 * @since 2024-09-20 19:47:08
 */
@Slf4j
@Service
public class SysPermissionsServiceImpl extends ServiceImpl<SysPermissionsMapper, SysPermissions> implements SysPermissionsService {
    @Override
    public Result buildMenuTree() {
        // 获取所有菜单
        List<SysPermissions> allMenus = baseMapper.getAllMenus();

        // 创建一个映射，用于快速查找子菜单
        Map<Integer, SysPermissions> menuById = allMenus.stream()
                .collect(Collectors.toMap(SysPermissions::getId, menuItem -> menuItem));
        List<Map<String, Object>> menu = new ArrayList<>();
        for (SysPermissions sysPermissions : allMenus) {
            if (sysPermissions.getParentId() == null) { // 只处理顶级菜单
                Map<String, Object> menuMap = new HashMap<>();
                menuMap.put("id", sysPermissions.getId());
                // 检查顶级菜单是否有子菜单
                menuMap.put("name", sysPermissions.getName());
                menuMap.put("code", sysPermissions.getCode());
                menuMap.put("createTime", sysPermissions.getCreateTime());
                List<Map<String, Object>> children = buildChildren(sysPermissions.getId(), allMenus, menuById);
                if (!children.isEmpty()) { // 只有当子菜单列表非空时才添加children字段
                    menuMap.put("children", children);
                }
                menu.add(menuMap);
            }
        }

        return Result.success("查询成功", menu);
    }

    @Override
    public Result insert(SysPermissions sysPermissions) {
        QueryWrapper<SysPermissions> queryWrapper = new QueryWrapper<>();
        queryWrapper.or(orWrapper -> {
            orWrapper.eq("name", sysPermissions.getName()).or().eq("code", sysPermissions.getCode());
        });
        List<SysPermissions> list = baseMapper.selectList(queryWrapper);
        if (!list.isEmpty()) {
            return Result.error("字典已存在，请检查");
        } else {
            // 插入新记录
            baseMapper.insert(sysPermissions);
            return Result.success("添加成功", "");
        }
    }

    @Override
    public Result update(SysPermissions sysPermissions) {
        // 获取当前要更新的记录的 ID
        Integer currentId = sysPermissions.getId();

        // 创建查询包装器
        QueryWrapper<SysPermissions> queryWrapper = new QueryWrapper<>();

        // 构建 OR 条件：name 或 code 任意一个存在，并且排除当前记录的 ID
        queryWrapper.or(orWrapper -> {
            orWrapper.eq("name", sysPermissions.getName());
            orWrapper.eq("code", sysPermissions.getCode());
        }).ne(currentId != null, "id", currentId);

        // 执行查询
        List<SysPermissions> list = baseMapper.selectList(queryWrapper);

        // 检查是否存在
        if (!list.isEmpty()) {
            return Result.error("字典已存在，请检查");
        } else {
            // 更新记录
            baseMapper.updateById(sysPermissions);
            return Result.success("更新成功", "");
        }
    }

    private List<Map<String, Object>> buildChildren(int parentId, List<SysPermissions> allMenus, Map<Integer, SysPermissions> menuById) {
        List<Map<String, Object>> children = new ArrayList<>();
        for (SysPermissions sysPermissions : allMenus) {
            if (sysPermissions.getParentId() != null && sysPermissions.getParentId().equals(parentId)) {
                Map<String, Object> childMap = new HashMap<>();
                childMap.put("id", sysPermissions.getId());
                childMap.put("name", sysPermissions.getName()); // 子菜单包含 name 字段
                childMap.put("code", sysPermissions.getCode());
                childMap.put("createTime", sysPermissions.getCreateTime());
                childMap.put("parentId", sysPermissions.getParentId());
                // 递归构建子菜单
                List<Map<String, Object>> subChildren = buildChildren(sysPermissions.getId(), allMenus, menuById);
                if (!subChildren.isEmpty()) { // 只有当子菜单列表非空时才添加children字段
                    childMap.put("children", subChildren);
                }
                children.add(childMap);
            }
        }
        return children;
    }
}
